<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script>
        //照片上传到canvas画布中，以便通过Base64编码转换为字符存放到数据库中。
        function previewFile() {
            var file = document.querySelector('input[type=file]').files[0];
            //var _data = document.getElementById("imgshow").getElementsByTagName('img')[0];

            //var file = document.querySelector(".addimg").files[0];
            console.log(file);
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function(e) {
                var dataURL = reader.result;
                var image = new Image();
                image.src = dataURL;
                image.onload = function() {
                    //var canvas = document.createElement('canvas');
                    var canvas = document.getElementById("myCanvas");
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage(this, 100, 100, 100, 100);
                }
            }
        }

        function showImg(obj) {
            var files = obj.files
            getImgsByFileReader(document.getElementById("imgshow"), files)
        }

        function getImgsByFileReader(el, files) {
            for (var i = 0; i < files.length; i++) {
                let img = document.createElement('img')
                img.setAttribute('style', 'width: 40px; height: 40px; vertical-align: middle; margin-right: 5px;')
                el.appendChild(img)
                var reader = new FileReader()
                reader.onload = function(e) {
                    img.src = e.target.result
                }
                reader.readAsDataURL(files[i])
            }
        }

        //在DIV中显示照片方法
    </script>
</head>

<body>
    <div class="mainDiv" width="250" height="400" style="border:1px solid #0659f1">
        <input type="file" class="addimg " accept="image/* " onchange="previewFile() "><br/><br/><br/>
        <!-- <button onclick="File() ">上传</button><br/><br/> -->
        <canvas id="myCanvas" width="250" height="300" style="border:1px solid #f70b0b; " onclick="f() ">画布</canvas>
    </div>

</body>

</html>